from re import S
from PySide6.QtWidgets import QPlainTextEdit
from PySide6.QtGui import QGuiApplication,QDesktopServices
from PySide6.QtCore import QPoint,Qt,Signal
from custome_content_menu import ContentMenu


class PlainTextEdit(QPlainTextEdit):
    """自定义纯文本编辑

    :param QPlainTextEdit: PySide6 纯文本编辑
    """
    hasText = Signal(bool)

    def __init__(self):
        """初始化"""
        super().__init__()
        self.__init_signal_event()
        self.__init_content_menu_event()

        # 初始化一个 剪贴板
        self.clipbaord_ = QGuiApplication.clipboard()
        self.menu = ContentMenu(self)

    def __init_signal_event(self):
        """初始化"""
        self.textChanged.connect(self.__has_text)

    def __has_text(self) -> bool:
        """判断是否有文本
        """
        self.hasText.emit(True) if self.toPlainText() else self.hasText.emit(False)

    def __init_content_menu_event(self):
        """初始化上下文菜单"""
        self.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu)
        self.customContextMenuRequested.connect(self.show_custome_content_menu)

    def show_custome_content_menu(self,pos: QPoint):
        """显示自定义上下文菜单

        :param pos: customContextMenuRequested 传出的 QPoint 位置
        """
        self.menu.exec(pos)

    def set_event_bind(self):
        """设置事件绑定"""
        # 设置状态 撤销、剪切、复制、粘贴、删除、全选
        self.undoAvailable.connect(self.menu.undo_action.setEnabled)
        self.copyAvailable.connect(self.menu.cut_action.setEnabled)
        self.copyAvailable.connect(self.menu.copy_action.setEnabled)
        self.clipbaord_.dataChanged.connect(self.reset_paste_state)
        self.copyAvailable.connect(self.menu.delete_action.setEnabled)
        self.hasText.connect(self.menu.select_all.setEnabled)

        #  撤销、剪切、复制、粘贴、删除 、全选 使用Bing搜索
        self.menu.undo_action.triggered.connect(self.undo)
        self.menu.cut_action.triggered.connect(self.cut)
        self.menu.copy_action.triggered.connect(self.copy)
        self.menu.paste_action.triggered.connect(self.paste)
        self.menu.delete_action.triggered.connect(self.clear)
        self.menu.select_all.triggered.connect(self.selectAll)
        self.menu.bing_search_action.triggered.connect(self.bing_search)
    
    def reset_paste_state(self):
        """重新设置粘贴状态"""
        clipbaord_text = self.clipbaord_.text()
        if clipbaord_text:
            self.menu.paste_action.setEnabled(True)
        else:
            self.menu.paste_action.setEnabled(False)
    
    def bing_search(self):
        """Bing搜索"""
        search_text = self.textCursor().selectedText()
        QDesktopServices.openUrl(f"https://cn.bing.com/search?q={search_text}")     